package com.mbt.deal.ui.widgets;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.mbt.deal.R;
import com.mbt.deal.api.Api;
import com.mbt.deal.api.ApiServer;
import com.mbt.deal.api.RxBus;
import com.mbt.deal.api.RxResultHelper;
import com.mbt.deal.api.RxSchedulers;
import com.mbt.deal.api.RxSubscriber;
import com.mbt.deal.bean.BaseBean;
import com.mbt.deal.bean.BaseDataBean;
import com.mbt.deal.bean.BaseListBean;
import com.mbt.deal.bean.KLinebean;
import com.mbt.deal.bean.NowPriceBean;
import com.mbt.deal.bean.NullBean;
import com.mbt.deal.ui.fragment.DealbuinessFragment2;
import com.mbt.deal.util.MyUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imlib.relinker.elf.Elf;
import lecho.lib.hellocharts.listener.ViewportChangeListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * @author Administrator
 * @createtime：2018/8/22 14:32
 */
public class TubiaoView extends LinearLayout {
    private static final String TAG = "TubiaoView";
    private Context mContext;
    private TextView tv_now_price;
    private TextView tv_max_price;
    private TextView tv_min_price;
    private TextView tv_date_now;
    private TextView tv_date_now_data;
    private CheckBox five_min;
    private CheckBox five_hour;
    private TextView shi_shi_alert;
    private TabLayout tab_layout;
    private LinearLayout ll_jiage_zhishi;
    private View view1;
    private View view2;
    private LineChartView chart;
    private boolean hasAxes = true;
    private boolean hasAxesNames = false;
    private Axis axisX;
    private Axis axisY;
    private int timeType = 1;
    private int responseTimeType = 1;

    List<AxisValue> xValues = new ArrayList<>();
    private boolean isBiss;
    private String coinid;
    private int pageNum = 1;
    private int totalSize;
    private static final int pageSize = 20;
    private float priceHight;
    private int minTime = 1440;

    List<Entry> entries = new ArrayList<>();

    public TubiaoView(Context context) {
        super(context);
        initView(context);
    }

    public TubiaoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public TubiaoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.k_line_layout, this, false);
        tv_now_price = view.findViewById(R.id.tv_now_price);
        tv_max_price = view.findViewById(R.id.tv_max_price);
        tv_min_price = view.findViewById(R.id.tv_min_price);
        tv_date_now = view.findViewById(R.id.tv_date_now);
        tv_date_now_data = view.findViewById(R.id.tv_date_now_data);
        shi_shi_alert = view.findViewById(R.id.shi_shi_alert);
        tab_layout = view.findViewById(R.id.tab_layout);
        ll_jiage_zhishi = view.findViewById(R.id.ll_jiage_zhishi);
        five_min = view.findViewById(R.id.cb_five_min);
        five_hour = view.findViewById(R.id.cb_five_hour);
        view1 = view.findViewById(R.id.view1);
        view2 = view.findViewById(R.id.view2);
        chart = view.findViewById(R.id.chart);
        addView(view);
        chart = (LineChartView) findViewById(R.id.chart);
        chart.setZoomEnabled(false);

        five_min.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    minTime = 1440;
                    pageNum = 1;
                    xValues = null;
                    view2.setVisibility(INVISIBLE);
                    view1.setVisibility(VISIBLE);
                    chart.setViewportChangeListener(null);
                    responseTimeType = timeType;
                    getdata();
                    shi_shi_alert.setVisibility(GONE);
                    tab_layout.setVisibility(VISIBLE);
                    ll_jiage_zhishi.setVisibility(VISIBLE);
                    five_hour.setChecked(false);
                }
            }
        });
        five_hour.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    minTime = 5;
                    pageNum = 1;
                    xValues = null;
                    responseTimeType = 1;
                    view2.setVisibility(VISIBLE);
                    view1.setVisibility(INVISIBLE);
                    chart.setViewportChangeListener(null);
                    getdata();
                    shi_shi_alert.setVisibility(VISIBLE);
                    tab_layout.setVisibility(GONE);
                    ll_jiage_zhishi.setVisibility(GONE);
                    five_min.setChecked(false);
                }
            }
        });
        tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int i = tab.getPosition();
                if (i == 0) {
                    timeType = 1;
                } else if (i == 1) {
                    timeType = 2;
                } else if (i == 2) {
                    timeType = 3;
                }
                pageNum = 1;
                xValues = null;
                responseTimeType = timeType;
                getdata();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }


    private void generateData(List<KLinebean> linebeans) {

        List<Line> lines = new ArrayList<Line>();
        int numberOfLines = 1;
        List<PointValue> values = null;
        for (int i = 0; i < numberOfLines; ++i) {

            values = new ArrayList<PointValue>();
            for (int j = 0; j < linebeans.size(); j++) {
                int newIndex = j;
                Log.i(TAG, "generateData: newIndex=" + newIndex);
                values.add(new PointValue(newIndex, Float.parseFloat(linebeans.get(j).getPricehigh())));
            }

            Line line = new Line(values);
            line.setColor(ChartUtils.COLORS[i]);
            line.setShape(ValueShape.CIRCLE);
            line.setCubic(false);//曲线是否平滑，即是曲线还是折线
            line.setFilled(false);//是否填充曲线的面积
            line.setHasLabels(false);//曲线的数据坐标是否加上备注
            line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
            line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
            line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
            lines.add(line);
        }

        LineChartData data = new LineChartData(lines);

        if (hasAxes) {
            axisX = new Axis();
            axisY = new Axis().setHasLines(true);
            if (hasAxesNames) {
                axisX.setName("Axis X");
                axisY.setName("Axis Y");
            }
            setxValues(linebeans);
            data.setAxisXBottom(axisX);
            data.setAxisYLeft(axisY);

        } else {
            data.setAxisXBottom(null);
            data.setAxisYLeft(null);
        }

        data.setBaseValue(Float.NEGATIVE_INFINITY);
        chart.setLineChartData(data);

        final float lastXValue = values.get(values.size() - 1).getX();
        Viewport v = new Viewport(chart.getMaximumViewport());
        v.left = 0;
        v.right = 9;
        chart.setCurrentViewport(v);
        chart.setViewportChangeListener(new ViewportChangeListener() {
            @Override
            public void onViewportChanged(Viewport viewport) {
                Log.i(TAG, "onViewportChanged: " + viewport.toString());
                if (!isBiss && viewport.right == lastXValue && lastXValue < (totalSize - 1)) {
                    isBiss = true;
                    pageNum++;
                    loadData();
                }
            }
        });
    }

    /**
     * 模拟网络请求动态加载数据
     */
    private void loadData() {
        LoadDialog.show(mContext);
        getdata();


    }


    private void addDataPoint(List<KLinebean> linebeans) {
        Line line = chart.getLineChartData().getLines().get(0);
        List<PointValue> values = line.getValues();
        int startIndex = values.size();

        for (int i = 0; i < linebeans.size(); i++) {
            int newIndex = startIndex + i;
            Log.i(TAG, "addDataPoint: newIndex=" + newIndex);
            values.add(new PointValue(newIndex, Float.parseFloat(linebeans.get(i).getPricehigh())));
        }

        line.setValues(values);
        List<Line> lines = new ArrayList<>();
        lines.add(line);
        LineChartData lineData = new LineChartData(lines);
        setxValues(linebeans);
        lineData.setAxisXBottom(axisX);
        lineData.setAxisYLeft(axisY);
        chart.setLineChartData(lineData);

        //根据点的横坐标实时变换X坐标轴的视图范围
        Viewport port = initViewPort(startIndex - 10, startIndex - 1);
//        chart.setMaximumViewport(port);
        chart.setCurrentViewport(port);

        final float lastXValue = values.get(values.size() - 1).getX();

        chart.setViewportChangeListener(new ViewportChangeListener() {
            @Override
            public void onViewportChanged(Viewport viewport) {
                Log.i(TAG, "onViewportChanged: " + viewport.toString());
                if (!isBiss && viewport.right == lastXValue && lastXValue < (totalSize - 1)) {
                    isBiss = true;
                    pageNum++;
                    loadData();
                }
            }
        });
    }

    /**
     * 设置视图
     *
     * @param left
     * @param right
     * @return
     */
    private Viewport initViewPort(float left, float right) {
        Viewport port = new Viewport();
        if (priceHight == 0) {
            priceHight = 100;
        }
        port.top = priceHight + 10;//Y轴上限，固定(不固定上下限的话，Y轴坐标值可自适应变化)
        port.bottom = 0;//Y轴下限，固定
        port.left = left;//X轴左边界，变化
        port.right = right;//X轴右边界，变化
        return port;
    }

    private void setxValues(List<KLinebean> linebeans) {
        if (xValues == null) {
            xValues = new ArrayList<>();
        }
        int valueSize = xValues.size();
        for (int i = 0; i < linebeans.size(); i++) {
            xValues.add(new AxisValue(valueSize + i).setLabel(linebeans.get(i).getshowTime(responseTimeType)));
        }
        axisX.setValues(xValues);
    }

    private float downx;
    private float downy;
    private boolean isIntercept = false;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            downx = ev.getX();
            downy = ev.getY();

        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            if (downx != 0 && downy != 0) {
                float dx = Math.abs(ev.getX() - downx);
                float dy = Math.abs(ev.getY() - downy);
                if (dx > dy) {
                    isIntercept = true;
                }
                downx = 0;
                downy = 0;
            }

        } else if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
            RxBus.getInstance().post(DealbuinessFragment2.SWIPEREFRESH_ON, "");
            isIntercept = false;
        }
        if (isIntercept) {
            getParent().requestDisallowInterceptTouchEvent(true);
            RxBus.getInstance().post(DealbuinessFragment2.SWIPEREFRESH_OFF, "");
        }
        return super.onInterceptTouchEvent(ev);
    }

    public void setCoinid(String coinid) {
        this.coinid = coinid;
        pageNum = 1;
        xValues = null;
        if (!isBiss) {
            isBiss = true;
            getdata();
            getNowPice();
        }

    }


    public void setPrice(String lowPice, String nowPrice, String heightPric) {
        tv_min_price.setText(lowPice);
        tv_now_price.setText(nowPrice);
        tv_max_price.setText(heightPric);
        priceHight = Float.parseFloat(heightPric);
    }

    private void getdata() {
        Map map = new HashMap();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("coinid", coinid);
        map.put("timeType", responseTimeType);
        Api.getServer(ApiServer.class).getPagePrice(MyUtils.getToken(mContext), map).compose(RxSchedulers.io_main()).compose(RxResultHelper.handleResult())
                .subscribe(new RxSubscriber<BaseListBean<KLinebean>>(mContext) {

                    @Override
                    public void _onNext(BaseListBean<KLinebean> nullBeanBaseListBean) {
                        if (pageNum == 1) {
                            totalSize = nullBeanBaseListBean.count;
                            generateData(nullBeanBaseListBean.data);

                        } else {
                            addDataPoint(nullBeanBaseListBean.data);
                        }
                    }

                    @Override
                    public void _onError(String message) {
                        if (pageNum > 1) {
                            pageNum--;
                        }
                    }

                    @Override
                    public void onCompleted() {
                        isBiss = false;
                        LoadDialog.dismiss(mContext);
                    }
                });
    }

    public void getNowPice() {
        Map map = new HashMap();
        map.put("id", coinid);
        Api.getServer(ApiServer.class).getNowPice(MyUtils.getToken(mContext), map).compose(RxSchedulers.io_main()).compose(RxResultHelper.handleResult())
                .subscribe(new RxSubscriber<BaseDataBean<NowPriceBean>>(mContext) {


                    @Override
                    public void _onNext(BaseDataBean<NowPriceBean> nowPriceBeanBaseDataBean) {
                        tv_date_now.setText(MyUtils.NowDate());
                        tv_date_now_data.setText("实时价格: " + nowPriceBeanBaseDataBean.data.getPricenow());
                    }

                    @Override
                    public void _onError(String message) {

                    }

                    @Override
                    public void onCompleted() {

                    }


                });
    }
}
